package annotation05;


import org.junit.Test;

import java.lang.reflect.Method;

/**
 * Class类中:
 *      public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass):判断类上是否存在指定的注解
 *      public <A extends Annotation> A getAnnotation(Class<A> annotationClass):获取指定的注解
 *
 * Method类中:
 *     public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass):判断类上是否存在指定的注解
 *     public <T extends Annotation> T getAnnotation(Class<T> annotationClass):获取指定的注解
 */
public class Demo {
    @Test
    public void testGetClassAnnotation() {
        //1.获取注解所在类的字节码对象
        Class<Person> personClass = Person.class;

        //2.判断类上是否存在指定的注解
        boolean flag = personClass.isAnnotationPresent(MyAnnotation.class);

        //3.如果存在该注解,我们再去获取该注解的属性
        if (flag) {
            //4.获取到指定的注解
            MyAnnotation annotation = personClass.getAnnotation(MyAnnotation.class);

            //5.获取注解上的属性
            System.out.println(annotation.value());
            System.out.println(annotation.name());
            System.out.println(annotation.color());
        }
    }

    @Test
    public void testGetMethodAnnotation() throws NoSuchMethodException {
        //1.获取注解所在类的字节码对象
        Class<Person> personClass = Person.class;

        //2.获取指定的方法
        Method getAgeMethod = personClass.getMethod("getAge");

        //3.判断该方法上是否有注解,如果有指定的注解再去获取
        if (getAgeMethod.isAnnotationPresent(MyAnnotation.class)) {
            MyAnnotation annotation = getAgeMethod.getAnnotation(MyAnnotation.class);
            System.out.println(annotation.value());
            System.out.println(annotation.name());
            System.out.println(annotation.color());

        }

    }
}
